﻿/*****************************************************************************/
/*****************************************************************************/
CREATE PROCEDURE [GrantManagement].[SaveGrant]
@GrantsOID          bigint          = NULL,
@GrantsVersion      rowversion      = NULL,
@CaseOID            bigint,
@ApplicantID        bigint,
@ValueOfGrant       decimal,
@CheckNumber        int             = NULL,
@NameOnCreditCard   varchar(128)    = NULL,
@GrantTypeID        bigint,
@StateID            bigint,
@PaymentTypeID      bigint,
@DeliveryMethodID   bigint,
@CustodianID        bigint          = NULL,
@CustodianAddressID bigint          = NULL

AS  

DECLARE @RetCode int,
        @RowCount int

-- 1. If new record (OID is not set)
IF ISNULL(@GrantsOID, 0) <= 0 
BEGIN
	-- 1.1. Perform insert (OID is identity).
	INSERT INTO dbo.Grants
	(CaseID, ApplicantID, ValueOfGrant, CheckNumber, NameOnCreditCard, GrantTypeID, StateID, PaymentTypeID, DeliveryMethodID, DeliverToPersonID, DeliverToAddressID, UpdatedDate, CreatedDate)
	VALUES
	(@CaseOID, @ApplicantID, @ValueOfGrant, @CheckNumber, @NameOnCreditCard, @GrantTypeID, @StateID, @PaymentTypeID, @DeliveryMethodID, @CustodianID, @CustodianAddressID, GETDATE(), GETDATE())

	-- 1.2. Determine OID of newly inserted object
	SET @GrantsOID = SCOPE_IDENTITY()
END

-- 2. If OID is set (existing record)
ELSE
BEGIN
	-- 2.1. Attempt updating object (using both OID and timestamp for concurrency reasons)
	UPDATE dbo.Grants
	SET CaseID = @CaseOID
	    ,ApplicantID = @ApplicantID
	    ,ValueOfGrant = @ValueOfGrant
	    ,CheckNumber = @CheckNumber
	    ,NameOnCreditCard = @NameOnCreditCard
	    ,GrantTypeID = @GrantTypeID
	    ,StateID = @StateID
	    ,PaymentTypeID = @PaymentTypeID
	    ,DeliveryMethodID = @DeliveryMethodID
        ,DeliverToPersonID = @CustodianID
        ,DeliverToAddressID = @CustodianAddressID
		,UpdatedDate = GETDATE()
	WHERE ((OID = @GrantsOID) AND (Version = @GrantsVersion))
    SELECT @RetCode = @@ERROR, @RowCount = @@ROWCOUNT
    IF (@RetCode <> 0) GOTO ExitError

	-- 2.2. If no records were found (and updated) - it means that
	-- another process had updated this record (therefore timestamp will be different)
	-- or record was deleted (OID not found)
	-- Either way, we need to raise exception
	IF @RowCount = 0
	BEGIN
		RAISERROR(99999, 16, 1, 'Grant' ) --WITH LOG
		GOTO ExitError
	END
END 

---------------------------------------------------------------------------------------------------
--	Return the values to the caller
---------------------------------------------------------------------------------------------------
SELECT OID AS 'GrantsOID', Version AS 'GrantsVersion'
FROM dbo.Grants
WHERE OID = @GrantsOID

RETURN(0)

ExitError:
	RETURN(1)


